//
//  ContentTableController.m
//  kyMusicPlayer
//
//  Created by 翁科宇 on 2018/5/14.
//  Copyright © 2018年 翁科宇. All rights reserved.
//

#import "ContentTableController.h"
#define kCustomRowCount 7

@interface ContentTableController ()
{
    SongInfo *songInfo;
}
//@property(nonatomic, strong)SongInfo *songInfo;

@property(nonatomic, strong)NSMutableArray *arrayList;
// the set of IconDownloader objects for each app
@property(nonatomic, strong)NSMutableDictionary *imageDownloadInProgress;
@property(nonatomic, strong)UIActivityIndicatorView *indicator;
@property(nonatomic, strong)MusicDownloader *downloader;

@end

@implementation ContentTableController

- (void)viewDidLoad {
    [super viewDidLoad];
    _downloader = [[MusicDownloader alloc] init];
    _downloader.isDataRequestFinish = NO;
    _imageDownloadInProgress = [NSMutableDictionary dictionary];
    songInfo = SongInfo.sharedManager;
    [self setUpBasic];
    [self setUpRefresh];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"LazyTableCell"];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"PlaceholderCell"];
    self.tableView.rowHeight = 70;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark --private Method--设置tableView
- (void)setUpBasic{
    self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(104, 0, 0, 0);
    self.tableView.tableFooterView = [self footerViewForSection:0];
    
}
//解决tableView最后显示不全的问题
- (UITableViewHeaderFooterView *)footerViewForSection:(NSInteger)section{
    UITableViewHeaderFooterView *footerView = [[UITableViewHeaderFooterView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 120)];
    return footerView;
}


#pragma mark --private Method--初始化刷新控件
- (void)setUpRefresh{
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    [self.tableView.mj_header beginRefreshing];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}
//匹配类型
- (int8_t)matchingType{
    uint8_t type = '\0';//'\0'字符串结束标志
    if ([self.channelTitle isEqualToString:@"新歌"]) {
        type = NEW_SONG_LIST;
        return type;
    }else if ([self.channelTitle isEqualToString:@"热歌"]){
        type = HOT_SONG_LIST;
        return type;
    }else if ([self.channelTitle isEqualToString:@"经典"]){
        type = OLD_SONG_LIST;
        return type;
    }else if ([self.channelTitle isEqualToString:@"情歌"]){
        type = LOVE_SONG_LIST;
        return type;
    }else if ([self.channelTitle isEqualToString:@"网络"]){
        type = INTERNET_SONG_LIST;
        return type;
    }else if ([self.channelTitle isEqualToString:@"影视"]){
        type = MOVIE_SONG_LIST;
        return type;
    }else if ([self.channelTitle isEqualToString:@"欧美"]){
        type = EUROPE_SONG_LIST;
        return type;
    }else if ([self.channelTitle isEqualToString:@"Bill"]){
        type = BILLBOARD_MUSIC_LIST;
        return type;
    }else if ([self.channelTitle isEqualToString:@"摇滚"]){
        type = ROCK_MUSIC_LIST;
        return type;
    }else if ([self.channelTitle isEqualToString:@"爵士"]){
        type = JAZZ_MUSIC_LIST;
        return type;
    }else if ([self.channelTitle isEqualToString:@"流行"]){
        type = POP_MUSIC_LIST;
        return type;
    }
    else{
        return type;
    }
}
#pragma mark - /*** 刷新数据 ***/
// ---------------------------------
//    loadMoreData
//  Pull-Up(上拉)
// ---------------------------------
- (void)loadData{
    //一个数字占一个字节
    uint8_t type = [self matchingType];
    NSString *partOne = @"http://tingapi.ting.baidu.com/v1/restserver/ting?from=qianqian&version=2.1.0&method=baidu.ting.billboard.billList&format=json&";
    NSString *partTwo = [NSString stringWithFormat:@"type=%d&offset=0&size=%d", type, 20];
    NSString *urlString = [partOne stringByAppendingString:partTwo];
    [self loadDataForType:1 withURL:urlString];
}

// ---------------------------
//    loadMoreData
//  Pull-Down(下拉)
// ---------------------------
- (void)loadMoreData{
    uint8_t type = [self matchingType];
    NSString *partOne = @"http://tingapi.ting.baidu.com/v1/restserver/ting?from=qianqian&version=2.1.0&method=baidu.ting.billboard.billList&format=json&";
    NSString *partTwo = [NSString stringWithFormat:@"type=%d&offset=%lu&size=%d",type,self.arrayList.count, 20];
    NSString *urlString = [partOne stringByAppendingString:partTwo];
    [self loadDataForType:2 withURL:urlString];
    
}

// --------------------------------------------------------------------
//    loadDataForType:(int)loadingType withURL:(NSString *)urlString
//  Loading data through Pull-Up and Pull-Down
// --------------------------------------------------------------------
- (void)loadDataForType:(NSInteger)loadingType withURL:(NSString *)urlString{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *path = urlString;
    __weak typeof(self) weakSelf = self;
    [manager GET:path parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSArray *array = [responseObject objectForKey:@"song_list"];
            NSArray *loadSongArray = [HotSongInfo mj_objectArrayWithKeyValuesArray:array];
            if (loadingType == 1) {
                weakSelf.arrayList = [loadSongArray mutableCopy];
                //[weakSelf.arrayList addObject:loadSongArray];
                [weakSelf.tableView.mj_header endRefreshing];
            }else if (loadingType == 2){
                if (weakSelf.arrayList.count >= 100) {
                    [weakSelf.tableView.mj_footer endRefreshing];
                    return;
                }
                [weakSelf.arrayList addObjectsFromArray:loadSongArray];
                [weakSelf.tableView.mj_footer endRefreshing];
            }
            self->songInfo.isDataRequestFinish = YES;
            self->songInfo.mSongs = weakSelf.arrayList;
            [weakSelf.tableView reloadData];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error--%@",error);
    }];
}
// --------------------------------------
//    startIconDownload:forIndexPath:
// --------------------------------------
- (void)startIconDownload:(HotSongInfo *)info forIndexPath:(NSIndexPath *)indexPath{
    MusicDownloader *downloader = self.imageDownloadInProgress[indexPath];
    if (downloader == nil) {
        downloader = [[MusicDownloader alloc] init];
        downloader.hotSongInfo = info;
        [downloader setCompletionHandler:^{
            UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            cell.imageView.image = info.albumImage_small;
            [self.imageDownloadInProgress removeObjectForKey:indexPath];
        }];
        self.imageDownloadInProgress[indexPath] = downloader;
        [downloader startDownload];
    }
}
//这种方法用于防止用户滚动到一组没有应用程序图标的单元格中
- (void)loadImagesForOnScreenRows{
    if (self.arrayList.count > 0) {
        NSArray *visiblePaths = [self.tableView indexPathsForVisibleRows];
        for (NSIndexPath *indexPath in visiblePaths) {
            HotSongInfo *info = self.arrayList[indexPath.row];
            if (info.albumImage_small == nil) {
                [self startIconDownload:info forIndexPath:indexPath];
            }
        }
    }
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.arrayList.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = nil;
    if (self.arrayList.count == 0 && indexPath.row == 0) {
       cell = [tableView dequeueReusableCellWithIdentifier:@"PlaceholderCell" forIndexPath:indexPath];
    }
    else{
        cell = [tableView dequeueReusableCellWithIdentifier:@"LazyTableCell" forIndexPath:indexPath];
        if (self.arrayList.count > 0) {
            HotSongInfo *info = self.arrayList[indexPath.row];
            cell.textLabel.text = info.title;
            cell.detailTextLabel.text = info.author;
            if (info.albumImage_small == nil) {
                if (self.tableView.dragging == NO && self.tableView.decelerating == NO) {
                    [self startIconDownload:info forIndexPath:indexPath];
                }
                cell.imageView.image = [UIImage imageNamed:@"Placeholder"];
            }
            else{
                cell.imageView.image = info.albumImage_small;
            }
        }
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    HotSongInfo *info = self.arrayList[indexPath.row];
    NSLog(@"你选择了《%@》这首歌",info.title);
    [songInfo setSongInfo:info];
    [songInfo getSelectedSong:info.song_id index:indexPath.row];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (!decelerate) {
        [self loadImagesForOnScreenRows];
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [self loadImagesForOnScreenRows];
}
@end
